package com.cee.controller;

import com.cee.common.result.Result;
import com.cee.common.result.ResultCodeEnum;
import com.cee.dto.AddExamSubjectDTO;
import com.cee.exception.CeeException;
import com.cee.model.ExamOneSelect;
import com.cee.service.ExamOneSelectService;
import com.cee.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/examOneSelect")
public class ExamOneSelectController {

    @Autowired
    private ExamOneSelectService examOneSelectService;

    @Autowired
    private ExamService examService;


    @GetMapping("/delete")
    public Result deleteExamOneSelect(Integer id, Integer ceeExamId){
        examOneSelectService.deleteExamOneSelectById(id);

        // 更新总分
        examService.countGradeAndUpdate(ceeExamId);
        return Result.ok();
    }


    @PostMapping("/update")
    public Result updateExamOneSelect(@RequestBody ExamOneSelect examOneSelect){

        examOneSelectService.updateExamOneSelect(examOneSelect);

        // 更新总分
        examService.countGradeAndUpdate(examOneSelect.getCeeExamId());
        return Result.ok();
    }

    @PostMapping("/add")
    public Result saveExamOneSelect(@RequestBody AddExamSubjectDTO addExamSubjectDTO){

        if (addExamSubjectDTO.getList()==null || addExamSubjectDTO.getExamId() == null
                || addExamSubjectDTO.getGrade() == null){
            throw new CeeException(ResultCodeEnum.PARAM_ERROR);
        }

        for (Integer id : addExamSubjectDTO.getList()){
            ExamOneSelect examOneSelect = new ExamOneSelect();
            examOneSelect.setCeeOneSelectId(id);
            examOneSelect.setCeeExamId(addExamSubjectDTO.getExamId());
            examOneSelect.setGrade(addExamSubjectDTO.getGrade());

            examOneSelectService.saveExamOneSelect(examOneSelect);
        }

        // 更新总分
        examService.countGradeAndUpdate(addExamSubjectDTO.getExamId());

        return Result.ok();
    }

}
